<template>
  <div
    style="position: absolute;background-color: #fff;padding-top:36px;overflow: hidden;width: 100%;height: 100%;"
  >
    <div style="position: absolute;top:6px;left: 10px;right: 10px;">
      <!-- <input
        type="text"
        :id="treeId + '_search'"
        v-model="treeSearchValue"
        @keydown="searchEnter"
        style="width:100%;"
        placeholder="请输入部门名称"
      /> -->
      <SearchBox
        :id="treeId + '_search'"
        style="width:100%;font-size:12px"
        placeholder="请输入部门名称"
        v-model="treeSearchValue"
        @search="searchBtn($event)"
        @keydown="searchEnter"
      >
        <Addon>
          <span
            v-if="treeSearchValue"
            class="textbox-icon icon-clear"
            title="Clear value"
            @click="treeSearchValue = null"
          ></span>
        </Addon>
      </SearchBox>
    </div>

    <div :style="treeStyle">
      <div class="areaTree">
        <ul :id="treeId" class="ztree otherStyle" @click="clickTreeUl(treeId)"></ul>
      </div>
    </div>
  </div>
</template>

<script>
// import treeApi from "@/api/tree";
import sysApi from "@/api/sys";

export default {
  // name: "deptTree",
  props: {
    enable: {
      type: Boolean,
      default: true
    },
    checkbox: Boolean,
    onZTreeClick: Function,
    onZTreeCheck: Function,
    treeHeight: String,
    treeId: String,
    dataUrl: {
      type: String,
      default: "api/dept/tree/zTree"
    },
    httpMethod: {
      type: String,
      default: "get"
    },
    filter: String
  },
  data() {
    return {
      selected: null,
      checked: "",
      treeSearchValue: "",
      treeStyle: {
        overflow: "hidden",
        border: "0",
        borderTopWidth: "1px",
        borderStyle: "solid",
        borderColor: "#BDC3C7",
        height: "100%"
      },
      setting: {
        data: {
          simpleData: {
            enable: true,
            idKey: "id"
          }
        },
        callback: {
          onClick: this.onTreeClick,
          onCheck: this.onTreeCheck
        },
        check: {
          enable: this.enable,
          chkboxType: { Y: "s", N: "ps" }
        },
        view: {
          showLine: true,
          showTitle: true,
          showIcon: true,
          nameIsHTML: true //允许name支持html
        }
      },
      zNodes: [
        {
          id: 1,
          name: "父节点1",
          children: [
            { id: 2, name: "子节点1", checked: true, isParent: false },
            { id: 3, name: "子节点2", title: "abc" }
          ]
        }
      ]
    };
  },
  beforeMount() {
    /* eslint-disable */
            // $(this.treeId+"_search").bind('input propertychange', function () {
            //     var _keywords = $(this).val();
            //     this.searchNodeLazy(_keywords); //call lazy load
            // });
            // $(this.treeId+"_search").keydown(function(e){
            //     alert(e.which);
            // });
        },
        async mounted() {
            this.loadData();
        },
        methods: {
            async loadData() {
                // var response = await treeApi.getZTree();

                const response = await sysApi.getData(
                    this.dataUrl,
                    this.httpMethod,
                    this.filter
                );

                if (response.success) {
                    this.zNodes = response.result;
                    /* eslint-disable */
                    $.fn.zTree.init($("#" + this.treeId), this.setting, this.zNodes);

                    if(this.zNodes) {
                      const zTreeObj = $.fn.zTree.getZTreeObj(this.treeId);
                      if(zTreeObj) {
                        // 默认全选
                        zTreeObj.checkAllNodes(true);
                        const rootNodes = zTreeObj.getNodesByParam('level', '0');//get all root nodes
                        // zTreeObj.expandAll(false);
                        zTreeObj.expandNode(rootNodes[0], true);
                      }
                    }
                } else {
                    // alert(response.message);
                }
            },
            onTreeClick(event, treeId, treeNode) {
                if (this.onZTreeClick) {
                    this.onZTreeClick(treeNode);
                }
            },
            onTreeCheck(event, treeId, treeNode) {
                var treeObj = $.fn.zTree.getZTreeObj(this.treeId);
                var nodes = treeObj.getCheckedNodes(true);
                if (this.onZTreeCheck) {
                    this.onZTreeCheck(nodes);
                }
            },
            onCheck(nodes) {
                const deptSerial = nodes.map(item => {
                    return item.key;
                });
                this.checked = deptSerial;
                //check 没有选中复选框事件，这里就不回调方法了
            },
            getCheckedNodeIdString() {
                const treeObj = $.fn.zTree.getZTreeObj(this.treeId);
                // console.log(treeObj.getCheckedNodes(true));
                // var nodes = treeObj.transformToArray(treeObj.getCheckedNodes(true));
                // console.log(treeObj.transformToArray(treeObj.getCheckedNodes(true)));
                // console.log(treeObj.transformTozTreeNodes(treeObj.getCheckedNodes(true)));
                let dept = "";
                if(treeObj){
                  const nodes = treeObj.getCheckedNodes(true);
                  nodes.forEach((node, index, array) => {
                      return (dept += node.id + ",");
                  });
                }
                // console.log(dept.substring(0, dept.length - 1));
                return dept.substring(0, dept.length - 1);
            },
            // 这个封装的比较早，不敢动，不知道会不会影响其他地方；是获取复选框勾选的节点
            getSelectedNodes() {
              const treeObj = $.fn.zTree.getZTreeObj(this.treeId);
              if(treeObj) {
                let selectedNodes = treeObj.getCheckedNodes(true);

                if (selectedNodes.length == 0) {
                  // 如果复选框的没有获取到节点就返回选择的节点
                  selectedNodes = treeObj.getSelectedNodes(true);
                }
                return selectedNodes;
              }
            },
            
            searchBtn(event){
              this.searchNodes(this.treeSearchValue);
            },
            searchEnter(event) {
                if (event.which === 13) {
                    this.searchNodes(this.treeSearchValue);
                }
            },
            clickTreeUl(treeId){
              // console.log(treeId);
            },
            searchNodes(value) {
                // var treeObj = $.fn.zTree.getZTreeObj("deptTree");
                // var nodes = treeObj.getNodesByParamFuzzy("name", value, null);
                // console.log(nodes);

                // function filter(node) {
                //     // console.log(node.name);
                //     return node.name.indexOf(value) > -1;
                // }
                //
                // var treeObj = $.fn.zTree.getZTreeObj(this.treeId);
                // // var node = treeObj.getNodesByFilter(filter, true); // 仅查找一个节点
                // var nodes = treeObj.getNodesByFilter(filter, false); // 查找节点集合
                // // console.log(nodes);
                // $.fn.zTree.init($("#" + this.treeId), this.setting, nodes);
                // console.log(value);
                this.searchNodeLazy(value)
            },
            zTreeFilter(zTreeObj, _keywords, callBackFunc) {
                if (!_keywords) {
                    _keywords = ''; //default blank for _keywords
                }

                const isHighLight = true;//default true, only use false to disable highlight
                const isExpand = true; // not to expand in default
                zTreeObj.setting.view.nameIsHTML = isHighLight; //allow use html in node name for highlight use

                var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; //js meta characters
                var rexMeta = new RegExp(metaChar, 'gi');//regular expression to match meta characters
                var nameKey = zTreeObj.setting.data.key.name; //get the key of the node name
                // function to find the matching node
                function filterFunc(node) {
                    if (node && node.oldname && node.oldname.length > 0) {
                        node[nameKey] = node.oldname; //recover oldname of the node if exist
                    }
                    zTreeObj.updateNode(node); //update node to for modifications take effect
                    if (_keywords.length == 0) {
                        //return true to show all nodes if the keyword is blank
                        zTreeObj.showNode(node);
                        zTreeObj.expandNode(node, isExpand);
                        return true;
                    }
                    //transform node name and keywords to lowercase
                    if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase()) != -1) {
                        if (isHighLight) { //highlight process
                            //a new variable 'newKeywords' created to store the keywords information
                            //keep the parameter '_keywords' as initial and it will be used in next node
                            //process the meta characters in _keywords thus the RegExp can be correctly used in str.replace
                            var newKeywords = _keywords.replace(rexMeta, function (matchStr) {
                                //add escape character before meta characters
                                return '\\' + matchStr;
                            });
                            node.oldname = node[nameKey]; //store the old name
                            var rexGlobal = new RegExp(newKeywords, 'gi');//'g' for global,'i' for ignore case
                            //use replace(RegExp,replacement) since replace(/substr/g,replacement) cannot be used here
                            node[nameKey] = node.oldname.replace(rexGlobal, function (originalText) {
                                //highlight the matching words in node name
                                var highLightText =
                                    '<span style="color: whitesmoke;background-color: darkred;">'
                                    + originalText
                                    + '</span>';
                                return highLightText;
                            });
                            zTreeObj.updateNode(node); //update node for modifications take effect
                        }
                        zTreeObj.showNode(node);//show node with matching keywords
                        return true; //return true and show this node
                    }

                    zTreeObj.hideNode(node); // hide node that not matched
                    return false; //return false for node not matched
                }

                const nodesShow = zTreeObj.getNodesByFilter(filterFunc); //get all nodes that would be shown
                this.processShowNodes(zTreeObj, nodesShow, _keywords);//nodes should be reprocessed to show correctly
            },
            processShowNodes(zTreeObj, nodesShow, _keywords) {
                if (nodesShow && nodesShow.length > 0) {
                    //process the ancient nodes if _keywords is not blank
                    if (_keywords.length > 0) {
                        $.each(nodesShow, function (n, obj) {
                            let pathOfOne = obj.getPath();//get all the ancient nodes including current node
                            if (pathOfOne && pathOfOne.length > 0) {
                                //i < pathOfOne.length-1 process every node in path except self
                                for (let i = 0; i < pathOfOne.length - 1; i++) {
                                    zTreeObj.showNode(pathOfOne[i]); //show node
                                    zTreeObj.expandNode(pathOfOne[i], true); //expand node
                                }
                            }
                        });
                    } else { //show all nodes when _keywords is blank and expand the root nodes
                        const rootNodes = zTreeObj.getNodesByParam('level', '0');//get all root nodes
                        zTreeObj.expandAll(false);
                        zTreeObj.expandNode(rootNodes[0], true);

                        // $.each(rootNodes, function (n, obj) {
                        //     console.log(obj.isParent);
                        //     console.log(obj.name);
                        //     zTreeObj.expandNode(obj, false); //expand all root nodes
                        // });
                    }
                }
            },
            searchNodeLazy(_keywords) {


                // let timeoutId = null;
                // let lastKeyword = '';

                // if (timeoutId) {
                //     //clear pending task
                //     clearTimeout(timeoutId);
                // }
                const zTreeObj = $.fn.zTree.getZTreeObj(this.treeId);//get the ztree object by ztree id

                // if(_keywords === ''){
                //     const rootNodes = zTreeObj.getNodesByParam('level', '0');//get all root nodes
                //     $.each(rootNodes, function (n, obj) {
                //         zTreeObj.showNode(obj);
                //         zTreeObj.expandNode(obj, true); //expand all root nodes
                //     });
                // }

                const me = this;
                setTimeout(function () {
                    // if (lastKeyword === _keywords) {
                    //     return;
                    // }
                    me.zTreeFilter(zTreeObj, _keywords); //lazy load ztreeFilter function
                    // $(searchField).focus();//focus input field again after filtering
                    // lastKeyword = _keywords;
                }, 500);
            }
        }
    };
</script>

<style>
    @import "../../plugins/zTree/css/zTreeStyle/zTreeStyle.css";

    .areaTree {
        overflow: auto;
        height: 100%;
    }

    .otherStyle {
        display: table
    }

    .box-title {
        border-radius: 3px 3px 0 0;
        background-color: #f5f5f5;
    }

    .box-title a {
        color: #2fa4e7;
        text-decoration: none;
        font-size: 14px;
        display: block;
        padding: 8px 15px;
        cursor: pointer;
    }

    .box-title .fa {
        float: right;
        line-height: 20px;
    }
</style>
